package com.qifan.energy.base;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.qifan.energy.R;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.github.lzyzsd.jsbridge.DefaultHandler;

/**
 * 类名称: BaseWebViewActivity
 * 类描述: 封装的WebView加载H5页面的基类
 * 创建人: 陈书东
 * 创建时间: 2018/8/8 08:08
 * https://github.com/zang-chen/WebViewDemo
 */
public class BaseWebViewActivity extends BaseActivity {

    protected BridgeWebView webView;
    protected WebChromeClient chromeClient;
    protected WebViewClient webViewClient;
    protected ProgressBar progressBar;

    public boolean islandport = false;
    public ValueCallback<Uri> mUploadMessage;// 表单的数据信息
    public ValueCallback<Uri[]> mUploadCallbackAboveL;

    /*@Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        webView = (BridgeWebView) findViewById(R.id.webView);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        if (webView != null) {
            initWebView();
            initWebChromeClient();
            initWebViewClient();
        }
    }*/

    @Override
    protected int getLayoutId() {
        return R.layout.activity_base_webview;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        webView = (BridgeWebView) findViewById(R.id.webView);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        if (webView != null) {
            initWebView();
            initWebChromeClient();
            /*initWebViewClient();*/
        }
    }

    @Override
    protected void initData() {

    }

    private void initWebView() {
        WebSettings setting = webView.getSettings();
        //开启自动化测试
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.setWebContentsDebuggingEnabled(true);
        }

        //自定义UA
        String userAgent = setting.getUserAgentString();
        userAgent = userAgent + "WebViewDemo";
        setting.setUserAgentString(userAgent);

        /**
         *  Webview在安卓5.0之前默认允许其加载混合网络协议内容
         *  在安卓5.0之后，默认不允许加载http与https混合内容，需要设置webview允许其加载混合网络协议内容
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setting.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        //自动播放音频autoplay
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            setting.setMediaPlaybackRequiresUserGesture(false);
        }

        setting.setJavaScriptEnabled(true);//设置WebView是否允许执行JavaScript脚本,默认false
        setting.setSupportZoom(true);//WebView是否支持使用屏幕上的缩放控件和手势进行缩放,默认值true
        setting.setBuiltInZoomControls(true);//是否使用内置的缩放机制
        setting.setDisplayZoomControls(false);//使用内置的缩放机制时是否展示缩放控件,默认值true

        setting.setUseWideViewPort(true);//是否支持HTML的“viewport”标签或者使用wide viewport
        setting.setLoadWithOverviewMode(true);//是否允许WebView度超出以概览的方式载入页面,默认false
        setting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//设置布局,会引起WebView的重新布局(relayout),默认值NARROW_COLUMNS

        setting.setRenderPriority(WebSettings.RenderPriority.HIGH);//线程优先级(在API18以上已废弃。不建议调整线程优先级，未来版本不会支持这样做)
        setting.setEnableSmoothTransition(true);//已废弃,将来会成为空操作（no-op）,设置当panning或者缩放或者持有当前WebView的window没有焦点时是否允许其光滑过渡,若为true,WebView会选择一个性能最大化的解决方案。例如过渡时WebView的内容可能不更新。若为false,WebView会保持精度（fidelity）,默认值false。
        setting.setCacheMode(WebSettings.LOAD_NO_CACHE);//重写使用缓存的方式，默认值LOAD_DEFAULT
        setting.setPluginState(WebSettings.PluginState.ON);//在API18以上已废弃。未来将不支持插件,不要使用
        setting.setJavaScriptCanOpenWindowsAutomatically(true);//让JavaScript自动打开窗口,默认false

        //webview 中localStorage无效的解决方法
        setting.setDomStorageEnabled(true);//DOM存储API是否可用,默认false
        setting.setAppCacheMaxSize(1024 * 1024 * 8);//设置应用缓存内容的最大值
        String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
        setting.setAppCachePath(appCachePath);//设置应用缓存文件的路径
        setting.setAllowFileAccess(true);//是否允许访问文件,默认允许
        setting.setAppCacheEnabled(true);//应用缓存API是否可用,默认值false,结合setAppCachePath(String)使用

        //支持文件下载
        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                try {
                    Uri uri = Uri.parse(url);
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        /*webView.addJavascriptInterface(new AndroidJavaScript(), "csd");*/
        webView.setDefaultHandler(new DefaultHandler());
        webView.registerHandler("getCamera", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                Log.i("CSD", "getCamera:JS传递过来的值为" + data);
                function.onCallBack("JAVA注册并接收消息后发送给JS的回调:" + data);
            }
        });
        webView.registerHandler("getImage", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                Log.i("CSD", "getImage:JS传递过来的值为" + data);
                function.onCallBack("JAVA注册并接收消息后发送给JS的回调:" + data);
            }
        });
        webView.registerHandler("getVideo", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                Log.i("CSD", "getVideo:JS传递过来的值为" + data);
                function.onCallBack("JAVA注册并接收消息后发送给JS的回调:" + data);
            }
        });
        webView.registerHandler("getAudio", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                Log.i("CSD", "getAudio:JS传递过来的值为" + data);
                function.onCallBack("JAVA注册并接收消息后发送给JS的回调:" + data);
            }
        });
    }

    protected void initWebViewClient() {
        webViewClient = new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //return super.shouldOverrideUrlLoading(view, url);
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                /*注意：super句话一定要删除，或者注释掉，否则又走handler.cancel() 默认的不支持https的了。
                super.onReceivedSslError(view, handler, error);*/
                handler.proceed();// 接受所有网站的证书
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }
        };
        webView.setWebViewClient(webViewClient);
    }

    protected void initWebChromeClient() {
        chromeClient = new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (progressBar != null) {
                    if (newProgress == 100) {
                        progressBar.setVisibility(View.GONE);
                    } else {
                        progressBar.setVisibility(View.VISIBLE);
                        progressBar.setProgress(newProgress);
                    }
                }
            }

            // For Android >= 5.0
            @Override
            public boolean onShowFileChooser(WebView webView,
                                             ValueCallback<Uri[]> filePathCallback,
                                             FileChooserParams fileChooserParams) {
                mUploadCallbackAboveL = filePathCallback;
                return true;
            }

            // For Android < 3.0
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                mUploadMessage = uploadMsg;
            }

            // For Android  >= 3.0
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                mUploadMessage = uploadMsg;
            }

            //For Android  >= 4.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUploadMessage = uploadMsg;
            }

            @Override
            public void onShowCustomView(View view, CustomViewCallback callback) {
                super.onShowCustomView(view, callback);
                if (islandport) {
                    return;
                }
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                webView.setVisibility(View.GONE);
                if (myView != null) {
                    callback.onCustomViewHidden();
                    return;
                }
                myView = view;
                myCallback = callback;
            }

            public View myView = null;
            public CustomViewCallback myCallback = null;

            @Override
            public void onHideCustomView() {
                super.onHideCustomView();
                if (myView == null) {
                    return;
                } else {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    myView.setVisibility(View.GONE);
                    webView.setVisibility(View.VISIBLE);
                    myCallback.onCustomViewHidden();
                    myView = null;
                }
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }
        };
        webView.setWebChromeClient(chromeClient);
    }

    public class AndroidJavaScript {

        @JavascriptInterface
        public void getCamera(String s) {
            //注意:此处JS交互非UI线程
            Log.i("CSD", "getCamera:JS传递过来的值为" + s);
        }

        @JavascriptInterface
        public void getImage(String s) {
            //注意:此处JS交互非UI线程
            Log.i("CSD", "getImage:JS传递过来的值为" + s);
        }

        @JavascriptInterface
        public void getVideo(String s) {
            //注意:此处JS交互非UI线程
            Log.i("CSD", "getVideo:JS传递过来的值为" + s);
        }

        @JavascriptInterface
        public void getAudio(String s) {
            //注意:此处JS交互非UI线程
            Log.i("CSD", "getAudio:JS传递过来的值为" + s);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            islandport = true;
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            islandport = false;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (webView != null) {
            webView.onResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (webView != null) {
            webView.onPause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (webView != null) {
            webView.setVisibility(View.GONE);
            webView.loadUrl("about:blank");
            webView.stopLoading();
            webView.setWebChromeClient(null);
            webView.setWebViewClient(null);
            webView.destroy();
            webView = null;
        }
    }
}
